using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Services;

namespace MainGame.GamePlay
{
  public abstract class AILayer : BoardLayer
  {
    public AILayer(Game game)
      : base(game)
    {
      UpdateOrder = (int)ComponentOrders.LOGIC;
    }

    public override void Initialize()
    {
      base.Initialize();
    }

    float ai_turn_timer;
    static readonly float AI_TURN_LENGTH = 0.1f;
    protected override void OnTurnChanged()
    {
      if (players[current_player_index].IsHuman == false)
        ai_turn_timer = AI_TURN_LENGTH;
    }

    float turn_over_timer;
    static readonly float TURN_OVER_INTERVAL = 0.5f;
    public override void Update(GameTime gameTime)
    {
      if (players[current_player_index].IsHuman == false)
      {
        if (ai_turn_timer > 0.0f)
        {
          ai_turn_timer -= gameTime.dt();
          if (ai_turn_timer <= 0.0f)
          {
            if (CurrentPlayer.Cards.Count > 0)
            {
              var played_card = 0;
              if (blocks.Any())
              {
                var b = blocks[0];
                if (b.Cards.Any())
                {
                  var color = b.Cards[0].Color;
                  if (CurrentPlayer.Cards.Any(c => c.Color == color))
                    played_card = CurrentPlayer.Cards.Select((c, i) => new { c, i }).First(c => c.c.Color == color).i;
                }
              }
              var first = CurrentPlayer.Cards[played_card];
              CurrentPlayer.Cards.RemoveAt(played_card);
              blocks.Add(new CardBlock() { Cards = new List<Card>() { first }, PlayedBy = CurrentPlayer });
            }
            turn_over_timer = TURN_OVER_INTERVAL;
          }
        }
        else
        {
          turn_over_timer -= gameTime.dt();
          if (turn_over_timer <= 0.0f)
            TurnOver();
        }
      }

      base.Update(gameTime);
    }
  }
}
